extends Main
var utils = globalData.infoDs["g_azurlaneUtils"]
var base = globalData.infoDs["g_azurlaneBase"]
var azurCtrl = globalData.infoDs["g_azurlane"]
var jiban = globalData.infoDs["g_azurlaneJiban"]
var achieve = globalData.infoDs["g_azurlaneAchieve"]
var gSys = globalData.infoDs["g_azurlaneSys"]
var server = globalData.infoDs["g_azurlaneServer"]
var relic = globalData.infoDs["g_azurlaneRelic"]

var startItemMsgScript = load(self.get_script().get_path().get_base_dir() + "/azurStartItemMsg.gd")
var startMsgScript = load(self.get_script().get_path().get_base_dir() + "/azurStartMsg.gd")
var talentBtnScript = load(self.get_script().get_path().get_base_dir() + "/azurTalentBtn.gd")
var jieSuanScript = load(self.get_script().get_path().get_base_dir() + "/azurJieSuan.gd")
var guanKaMsgScript = load(self.get_script().get_path().get_base_dir() + "/azurGuanKaMsg.gd")
var guanKaItemScript = load(self.get_script().get_path().get_base_dir() + "/azurGuanKaItem.gd")
var jiangLiMsgScript = load(self.get_script().get_path().get_base_dir() + "/azurJiangLiMsg.gd")
var optionScript = load(self.get_script().get_path().get_base_dir() + "/azurOption.gd")
var playerPanScript = load(self.get_script().get_path().get_base_dir() + "/azurPlayerPan.gd")

var difficult = load(self.get_script().get_path().get_base_dir() + "/azurDifficult.gd").new()

var startItemMsg
var startMsg
var keyboard

#障碍物
var obstacles = []

signal preCharaCastCdSkill(cha, sk)
signal onCharaDeathWord(cha)

func _ready():
	reloadKey()

func init(mode = 1):
	guankaMsg.maxLLv = 3
	if jinJieData.nowLv > 0:
		guankaMsg.maxLLv = 4
	if jinJieData.nowLv > 2:
		guankaMsg.maxLLv = 5

	player.maxLv = 25
	onStartGame()
	
func onStartGame():
	utils.changeScript(guankaMsg, guanKaMsgScript)
	$ui / player / hp.hide()
	$ui / player / gold.get_parent().rect_min_size = Vector2(300, 400)
	$ui / player / gold.rect_position = Vector2(100, 330)
	$ui / player / renKou.rect_position = Vector2(-30, 330)
	utils.changeScript(playerPan, playerPanScript)

	for i in range(4):
		var t = preload("res://ui/talentBtn/talentBtn.tscn").instance()
		t.name = "skill%d"%(i + 9)
		playerPan.get_node("GridContainer").add_child(t)

func reloadKey():
	keyboard = utils.loadScript("Keyboard")
	sys.main.get_node("ui").add_child(keyboard)

func loadInfo():
	onStartGame()
	var file = File.new()
	if file.open("user://data1/main.save", File.READ) == OK:
		var dic = parse_json(file.get_line())
		file.close()
		if dic == null:print_debug("读取存档错误")
		
		guankaMsg.infoSet(dic["guankaDic"])
		player.infoSet(dic["playDic"])
		base.data = dic["data"]
		
	deleteSave()

	chaData.rndPoolRs()
	base.gameStart(false)

	# playerPan.upHp(0)
	yield(sys.get_tree().create_timer(0.5), "timeout")
	if sys.main.has_node("ui/jiaoChen"):
		$ui / jiaoChen.queue_free()

func deleteSave():
	var dir = Directory.new()
	dir.remove("user://data1/main.save")
	
func saveInfo():
	#向碧蓝各文件发送save信号
	base.azurSave()

	var file = File.new()
	var dir = Directory.new()
	
	dir.make_dir_recursive("user://data1/")
	var dic = {
		guankaDic = guankaMsg.infoGet(), 
		playDic = player.infoGet(), 
		data = base.data
	}

	file.open("user://data1/main.save", File.WRITE)
	file.store_line(to_json(dic))
	file.close()

func upEvoChara():
	pass

func _on_dpsBtn_pressed():
	azurCtrl.battleStatis()

func upLv(val = 0):
	$ui / player / gold.text = "%s：%dG" % [tr("金币"), player.gold]
	player.renKouVal = chasNum()
	$ui / player / lv.text = "%s：%d | %d/%d" % [tr("等级"), player.lv, player.emp, player.maxEmp]
	$ui / player / renKou.text = "%s：%d/%d" % [tr("人口"), player.renKouVal, player.getRenKou()]

#刷新人口
func upPop():
	$ui / player / renKou.text = "%s：%d/%d" % [tr("人口"), player.renKouVal, player.getRenKou()]

var jieSuanFlag = true
func onCharaDel(cha):
	charaNum[cha.team - 1] = chasNum(cha.team)
	if charaNum[cha.team - 1] <= 0 and not isEnd and jieSuanFlag:
		isAiStart = false
		jieSuanFlag = false
		if cha.team == 1:
			isEnd = true
			yield (get_tree().create_timer(1), "timeout")
			var jiesuan = sys.newMsg("jieSuan")
			utils.changeScript(jiesuan, jieSuanScript)
			jiesuan.init(false)
		else:
			yield (get_tree().create_timer(1), "timeout")
			var msg = sys.newMsg("jiangLiMsg")
			utils.changeScript(msg, jiangLiMsgScript)
			msg.init(batType)
			yield (msg, "popup_hide")
			battleInit()


func insertEnemies(chas):
	var queueChas = []
	var yl = [1, 4, 0, 5, 2, 3]
	for cha in chas:
		var bl = false
		for y in yl:
			for x in range(min(5, cha.att.atkRan) - 1 + matW / 2, matW):
				var cell = Vector2(x, y)
				if matCha(cell) == null:
					setMatCha(cell, cha)
					bl = true;break
			if bl:break
		if matCha(cha.cell) != null and cha.cell != Vector2():
			cha.setDire(-1)
			cha.isDrag = true
			cha.position = map.map_to_world(Vector2(4, 1))
			emit_signal("onAddBatChara", cha)
			difficult.chaBonus(cha)
			appendTurnValue(cha)
		else:
			queueChas.append(cha)
	return queueChas

func fixEnemies(chas):
	var yl = [1, 4, 0, 5, 2, 3]
	var xl = [9, 8, 7, 6, 5]
	for cha in chas:
		var bl = false
		for y in yl:
			for x in xl:
				var cell = Vector2(x, y)
				if matCha(cell) == null:
					setMatCha(cell, cha)
					bl = true;break
			if bl:break
		if matCha(cha.cell) != null and cha.cell != Vector2():
			cha.setDire(-1)
			cha.isDrag = true
			cha.position = map.map_to_world(Vector2(4, 1))
			emit_signal("onAddBatChara", cha)
			difficult.chaBonus(cha)
			appendTurnValue(cha)

func battleReady(lvcs, lvzb, batType):
	turnValue = 0
	batChas = lvcs
	self.batType = batType
	difficult.battleReady()
	chaPool.clear()
	var dChas = []
	for i in batChas:
		var cha = newChara(i, 2)
		map.add_child(cha)
		dChas.append(cha)

	var queueChas = insertEnemies(dChas)
	fixEnemies(queueChas)

	var itemNum = lvzb / 3
	for i in range(itemNum):
		var id = itemData.rndGetEquip()
		var item:Item = sys.newItem(id)
		for j in range(100):
			var bl = false
			for k in dChas:
				if k.type == sys.CharaClass.BOSS:continue
				if k.lv == 2 and k.items.size() < 1 or (k.items.size() < (k.lv - 2)) or j > 50:
					if item.att.maxHp != 0 and (k.attCoe.maxHp > k.attCoe.atk or k.attCoe.maxHp > k.attCoe.mgiAtk):
						k.addItem(item);
						bl = true;
						break;
					elif item.att.atk != 0 and k.attCoe.maxHp < k.attCoe.atk:
						k.addItem(item);
						bl = true;
						break;
					elif item.att.mgiAtk != 0 and k.attCoe.maxHp < k.attCoe.mgiAtk:
						k.addItem(item);
						bl = true;
						break;
					elif k.attCoe.maxHp < k.attCoe.atk:
						k.addItem(item);
						bl = true;
						break;
					elif j > 50 and k.items.size() < 2:
						k.addItem(item);
						bl = true;
						break;
			if bl == true:break

	for i in dChas:
		if i.type == sys.CharaClass.BOSS:continue
		difficult.doEquipBonus(i)	
				
	lv += 1
	guanKaBtn.setBat()
	emit_signal("onBattleReady")
	upChaCell()
	azurCtrl.changeUpCha()
	azurCtrl.refreshTopLb()
signal onCharaBack
func _input(event):
	if get_global_mouse_position().x < 1325:
		mml = true
	var pos = map.get_local_mouse_position() + Vector2(map.cell_size.x / 2, map.cell_size.y)
	var cell = map.world_to_map(pos)
	if selCha != null:
		var w = matW
		if not sys.test:w = matW / 2
		if cell.x < 0:cell.x = 0;
		if cell.y < 0:cell.y = 0;
		if (pos.y < 630):
			selPos = map.map_to_world(cell) + $scene.position
			selImg.upSpr(selPos)
		else :
			selImg.position.y = - 1000;selImg.position.x = - 1000
		if event is InputEventMouseButton and event.pressed == false and selCha != null:
			if cell.x >= 0 and cell.x < w and cell.y >= 0 and cell.y < matH and not obstacles.has(cell):
				if selCha.isItem:
					var num = chasNum()
					if num < player.getRenKou() or matCha(cell) != null:
						var muCha = matCha(cell)
						setMatCha(cell)
						var bta = selCha.get_parent()
						bta.remove_child(selCha)
						bta.queue_free()
						var cha = selCha
						map.add_child(cha)
						cha.cell = cell
						cha.position = pos
						cha.isDrag = true
						cha.isItem = false
						setMatCha(cell, cha)
						cha.infoUp()
						if cell.x >= matW / 2:cha.team = 2;else:cha.team = 1
						if muCha != null:
							muCha.get_parent().remove_child(muCha)
							var bt = addBtItem(muCha)
							bt.get_parent().move_child(bt, selCha.get_parent().get_index())
						emit_signal("onPlaceChara", cha)
					else:sys.newBaseMsg("提示", "人口不足")
				else:
					var muCha = matCha(cell)
					var muCell = selCha.cell
					setMatCha(selCha.cell)
					setMatCha(cell)
					setMatCha(selCha.cell, muCha)
					setMatCha(cell, selCha)
					if cell.x >= matW / 2:selCha.team = 2;else :selCha.team = 1
			else:
				pos = get_global_mouse_position()
				var grid = $ui / Panel / ScrollContainer / GridContainer
				if pos.y > 600:
					pos = grid.get_local_mouse_position()
					var inx = int(pos.x / (144))
					inx = clamp(inx, 0, grid.get_child_count())
					if selCha.isItem:
						var node = selCha.get_parent()
						node.get_parent().move_child(node, inx)
					else:
						#角色从场上加入备战栏
						selCha.get_parent().remove_child(selCha)
						var bt = addBtItem(selCha)
						bt.get_parent().move_child(bt, inx)
						setMatCha(selCha.cell)
						emit_signal("onCharaBack", selCha)
				elif cell == Vector2(5, 2):
					emit_signal("onItemIn", selCha)
			audio.playSe("luo")
			selCha = null
			selImg.hide()
			$scene / bg / xian.hide()
			upLv()
	if selItem != null and event is InputEventMouseButton and event.pressed == false:
		var cha = matCha(cell)
		if cha != null and cha.team == 1:
			selItem.setCha(cha)
			emit_signal("onPlaceItem", selItem.item)
		elif cell == Vector2(5, 2):
			emit_signal("onItemIn", selItem)
		else :
			pos = get_global_mouse_position()
			var grid = $ui / Panel / ScrollContainer / GridContainer
			if pos.y > 650 and grid.get_child_count() > 0:
				pos = grid.get_local_mouse_position()
				var inx = int(pos.x / (144))
				inx = clamp(inx, 0, grid.get_child_count() - 1)
				selItem.setCha(grid.get_child(inx).get_child(0))
				emit_signal("onPlaceItem", selItem.item)
		selItem = null
		audio.playSe("luo")
#回合结束时执行此函数
func battleInit():
	var sl = []
	for x in range(matW):
		for y in range(matH):
			setMatCha(Vector2(x, y), null, true)
	for i in map.get_children():
		if i is Chara:
			sl.append(i)
	var delChas = []
	for cha in sl:
		if cha is Chara:
			if cha.team == 1 and batType == 2 and cha.isDeath and cha.isSumm == false:
				cha.revive()
				cha.att.hp = cha.att.maxHp
			cha.delAllBuff()
			if not cha.isDeath and not cha.isSumm:
				cha.cell = cha.oldCell
				cha.setDire(1)
				setMatCha(cha.cell, cha)
			else :
				if cha.team == 1 and cha.isSumm == false:
					delChas.append(cha)
					cha.cell = cha.oldCell
					
				else :cha.remove()
		
	yield (get_tree().create_timer(1), "timeout")
	var chaPs = [2, 5, 10, 15]
	for cha in delChas:
		if cha.lv <= 3 and false:
			var newId = ""
			if cha.lv > 3:
				newId = cha.baseId
			else :
				newId = chaData.getLvIds(cha.id, cha.lv - 1)
			
			var neff = cha.newEff("numHit")
			neff.setNorPos(cha.sprcPos)
			neff.scale = Vector2(1, 1)
			neff.init(0, cha)
			neff.play("tuiHua")
			
			cha.play("del")
			yield (get_tree().create_timer(0.7), "timeout")
			for i in range(2):
				var feiCha = preload("res://ex/eff/feiCha.tscn").instance()
				topUi.add_child(feiCha)
				feiCha.init(cha, Vector2(20 + 120 * i, 670), newId)
			
			cha.remove()
		else :
			var neff = cha.newEff("numHit")
			neff.setNorPos(cha.sprcPos)
			neff.scale = Vector2(1, 1)
			neff.init(0, cha)
			neff.play("tuiHua")
			cha.revive()
			cha.att.hp = cha.att.maxHp * 0.1
			# player.subHp(chaPs[cha.lv - 1])
	upChaCell()
	#单位回血
	if batType == 2:chasPlusHp(2, 2)
	else :chasPlusHp(0.4, 0.6)
	upLv()
	if batType == 2:
		batLLv += 1
		emit_signal("onBossEnd", batLLv)
	if batLLv >= guankaMsg.maxLLv:
		#游戏通关
		var jiesuan = sys.newMsg("jieSuan")
		utils.changeScript(jiesuan, jieSuanScript)
		jiesuan.init(true)
		emit_signal("onTongGuan", jinJieData.nowLv)
		#成就系统检查
		achieve.afterTongGuan()
		server.upload()
		deleteSave()
	else:
		guanKaBtn.setMap()
		if batType == 2:
			relic.open()
	emit_signal("onBattleEnd")
	jiban.onBattleEnd()
#开始游戏时执行此函数初始化战场
func initSt():
	chaData.rndPoolRs()
	itemData.rndPoolRs()
	guankaMsg.init()
	# player.addCha(newChara("biaoqiang-1"))
	# player.addCha(newChara("biaoqiang-2"))
	# player.addCha(newChara("biaoqiang-3"))
	# player.addCha(newChara("biaoqiang-4"))

	# player.addCha(newChara("lingbo-1"))
	# player.addCha(newChara("lingbo-2"))
	# player.addCha(newChara("lingbo-3"))
	

	# player.addCha(newChara("banrenma-4"))
	# player.addCha(newChara("xianghe-4"))
	# player.addCha(newChara("ruihe-4"))
	

	sys.main.player.addCha(sys.main.newChara("merchant"))
	player.addItem(sys.newItem("i_rare_equip_equipBox"))
	player.addItem(sys.newItem("i_ex_equip_huamingce"))
	# player.addItem(sys.newItem("i_gun_381"))
	
	upLv()
	if sys.test:
	# 	player.addCha(newChara("GSiren81qingraozhe"))
		# player.addCha(newChara("toolman"))
		for i in itemData.infos:
			if i.id == "i_ex_equip_plane":continue
			player.addItem(sys.newItem(i.id))
		for i in range(3):
			var it = sys.newItem("i_ex_equip_plane")
			it.postInit(false)
			player.addItem(it)

		# player.addCha(newChara("toolmanGM"))
		# player.addCha(newChara("lingbo-4"))
		# player.addCha(newChara("aierdeliqi-2"))
		# player.addCha(newChara("dafeng-2"))
		# player.addCha(newChara("laibixi-2"))

	# player.addItem(sys.newItem("i_equip_vh"))
	# player.addItem(sys.newItem("i_equip_vh"))
	# player.addItem(sys.newItem("i_equip_vh"))

	# player.addItem(sys.newItem("i_gun_203skc"))
	# player.addItem(sys.newItem("i_gun_203skc"))
	# player.addItem(sys.newItem("i_gun_203skc"))

	# player.addItem(sys.newItem("i_rare_equip_highMagnet"))
	# player.addItem(sys.newItem("i_rare_equip_highMagnet"))
		pass

	if sys.main.has_node("ui/jiaoChen"):
		$ui / jiaoChen.hide()

func newChara(id, team = 1):
	var cha = preload("res://core/chara.tscn").instance()
	cha.set_script(load("{dir}/{id}/{id}.gd".format({id = id, dir = chaData.infoDs[id].dir})))
	if not cha is Chara:
		print("error load chara, {dir}/{id}/{id}.gd".format({id = id, dir = chaData.infoDs[id].dir}))
		return null
	cha.id = id
	cha.team = team
	return cha

#获取当前关卡层数
func getStep():
	return guankaMsg.lvStep - 2

#当前关卡敌人总价值，影响战后资源结算
var turnValue = 0
func appendTurnValue(cha):
	turnValue += cha.lv
	if cha.type == sys.CharaClass.BOSS:
		turnValue += 50

#当player.addItem后，触发此函数
func addItem(item):
	var itemB = preload("res://ui/item/item.tscn").instance()
	itemGrid.add_child(itemB)
	itemB.init(item)
	itemB.isDrag = true
	if sys.isMin == false:
		itemB.rect_min_size *= 0.85
		itemB.get_node("TextureRect").rect_size *= 0.85
	if item.id == "i_ex_equip_plane":
		changePlaneIcon(itemB)

func isMatin(cell):
	if cell.x >= 0 and cell.y >= 0 and cell.x < matW and cell.y < matH and not obstacles.has(cell):
		return true
	else:
		return false

func changePlaneIcon(itemB):
	var im = Image.new()
	im.load("%s/%s/%s.png" % [itemData.infoDs[itemB.item.id].dir, itemB.item.id, itemB.item.planeId])
	var imt = ImageTexture.new()
	imt.flags = 4
	imt.create_from_image(im)
	itemB.get_node("TextureRect").texture = imt

#获得所有单位，0全部，1敌人，2友军
func getAllChas(team = 0):
	var result = []
	for x in range(matW):
		for y in range(matH):
			var cha = matCha(Vector2(x, y))
			if cha != null:
				if team == 0 or team == 1 and cha.team == 2 or team == 2 and cha.team == 1:
					result.append(cha)
	return result

#覆写父类函数
func battleStart():
	isAiStart = true
	jieSuanFlag = true
	battleTime = 0
	guanKaBtn.setNul()
	btChas.clear()
	charaNum[0] = 0;charaNum[1] = 0
	for x in range(matW):
		for y in range(matH):
			var cha = matCha(Vector2(x, y))
			if cha != null:
				charaNum[cha.team - 1] += 1
				cha.oldCell = cha.cell
				btChas.append(cha)
	jiban.onBattleStart()
	emit_signal("onBattleStart")
	audio.playSe("bat")
	dpsMsg.clear()
#覆写父类函数
func evoChara(cha, id):
	return evoCha(cha, id, true)

func evoCha(cha, id, extendsAtt = true):
	var afterEvoCha = newChara(id)
	if afterEvoCha != null:
		extendsEvo(afterEvoCha, cha, extendsAtt)
	return afterEvoCha

#进化后继承属性
func extendsEvo(afterEvoCha, cha, extendsAtt = true):
	var items = []
	for i in cha.items:
		items.append(i)
	afterEvoCha.maxItem = cha.maxItem
	var json = cha.toJson()
	var node = cha.get_parent()
	cha.remove()
	afterEvoCha.isItem = cha.isItem
	node.add_child(afterEvoCha)
	if afterEvoCha.lv > 3:
		afterEvoCha.baseId = cha.id
	afterEvoCha.position = cha.position
	afterEvoCha.cell = cha.cell
	afterEvoCha.isDrag = cha.isDrag
	if not afterEvoCha.isItem:
		setMatCha(afterEvoCha.cell, afterEvoCha)
	for i in items:
		afterEvoCha.addItem(i)
	upLv()
	emit_signal("onEvo", afterEvoCha)
	upLv()
	if extendsAtt:
		yield(sys.get_tree().create_timer(0.25), "timeout")
		afterEvoCha.extendsEvo(json)
		yield(sys.get_tree().create_timer(0.6), "timeout")
	
#覆写父类函数
func _on_optionBtn_pressed():
	var option = sys.newMsg("option")
	utils.changeScript(option, optionScript)
	option.popup()
#覆写父类函数
func rndF(obj):
	if rndLv >= 15:
		if chaData.rndPool.getItemW(obj) == 1:
			return true
	elif rndLv >= 3:
		if chaData.rndPool.getItemW(obj) == 3:
			return true
	elif rndLv < 3:
		return true
	else :return false

var time = 0
signal process
func _process(delta):
	if isAiStart:
		emit_signal("process", delta)
		time += delta
		if time >= 1:
			time -= 1
			upS()
var battleTime = 0
signal ups
func upS():
	battleTime += 1
	emit_signal("ups")

func matCha(cell):
	if isMatin(cell):
		return mat[cell.x][cell.y]
	else:return null

func setMatCha(cell, cha = null, force = false):
	cell.x = ceil(cell.x)
	cell.y = ceil(cell.y)
	if isMatin(cell):
		mat[cell.x][cell.y] = cha
		if cha != null:
			cha.cell = cell
		for i in sizCells:
			if isMatin(i+cell):
				var nCell = i + cell
				var nCellId = cellToId(nCell);var cellId = cellToId(cell)
				var nCha = matCha(i + cell)
				if aStar.are_points_connected(cellId,nCellId):
					aStar.disconnect_points(cellId,nCellId)
				if obstacles.has(cell) or obstacles.has(nCell):
					return
				if cha == null and nCha == null:
					aStar.connect_points(cellId,nCellId);
				elif cha == null and nCha != null:
					aStar.connect_points(nCellId,cellId,false);
				elif cha != null and nCha == null:
					aStar.connect_points(cellId,nCellId,false);
